package com.itheima.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.User;
import com.itheima.exception.loginException;
import com.itheima.jsonresult.JsonResult;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import com.itheima.util.JwtUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author linying
 * @since 2022-10-13
 */
@Log4j2
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public JsonResult login(User user) {
        // 设置判断条件
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", user.getPhone());
        wrapper.eq("code", user.getCode());

        // sql获取到的对象
        User one = getOne(wrapper);
        //判断是否用户密码是否存在
        if (one == null) {
            throw new loginException();
        }

        // 要创建token必须要有一个map，map的内容放入对象信息
        Map<String, String> map = new HashMap<>();
        map.put("user", JSON.toJSONString(one));
        String token = JwtUtils.getToken(map);

        // 把token存入emp对象
        one.setToken(token);

        // 把token存入redis数据库           key-token信息   value-该对象的信息
        redisTemplate.opsForValue().set(token, JSON.toJSONString(one), 1, TimeUnit.DAYS);

        //返回结果
        return JsonResult.success(one);
    }

    /**
     * 用户登出
     * @param request
     * @return
     */
    @Override
    public JsonResult loginout(HttpServletRequest request) {
        // 获取浏览器的token
        String token = request.getHeader("AuthorizationUser");
        // 删除仓库里响应的token
        redisTemplate.delete(token);

        return JsonResult.success(null);
    }

    /**
     * 发短信
     * @param user
     * @return
     */
    @Override
    public JsonResult sendMsg(User user) {
        //获取手机号
        String phone = user.getPhone();

        //判断手机号是否为空
        if (StrUtil.isNotEmpty(phone)){
            //生成验证码
            String code = RandomUtil.randomNumbers(6);
            log.info("code={}",code);
            //存入数据库
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("phone",user.getPhone());
            User one = getOne(wrapper);
            one.setCode(code);
            update(one,wrapper);

            //存入redis
            redisTemplate.opsForValue().set(phone,code,60,TimeUnit.SECONDS);

            //返回结果
            return JsonResult.success("手机验证码发送成功");

        }
        return JsonResult.error("短信发送失败");
    }


}
